// 组织架构
import React, { useState, useEffect } from 'react';
import useStore from '../../components/useStore';
import { 
  Button, Card, Form, notification, Input, Upload, DatePicker, 
  InputNumber, Modal, Spin, Divider, Row, Col 
} from 'antd';
import { DownloadOutlined, UploadOutlined, InfoCircleOutlined } from '@ant-design/icons';
import store from '../../untils/store';
import dayjs from 'dayjs';
import request from '../../untils/request'

const UpdateProductDelivery = () => {
  const { collapsed } = useStore();
  const { localUrl } = store();
  const [productDeliveryDetail, setproductDeliveryDetail] = useState({});
  const [productDeliveryForm] = Form.useForm();

  // 文件状态管理
  const [deliveryListFile, setDeliveryListFile] = useState(null);
  const [factoryAcceptanceReportFile, setFactoryAcceptanceReportFile] = useState(null);
  const [shipmentPlanFile, setShipmentPlanFile] = useState(null);
  const [productShipmentOrderFile, setProductShipmentOrderFile] = useState(null);
  const [customerAcceptanceReportFile, setCustomerAcceptanceReportFile] = useState(null);

  const [uploading, setUploading] = useState(false);

  // 文件上传前置处理
  const handleBeforeUpload = (fileType) => (file) => {
    switch(fileType) {
      case "delivery_list":
        setDeliveryListFile(file);
        break;
      case "factory_acceptance_report":
        setFactoryAcceptanceReportFile(file);
        break;
      case "shipment_plan":
        setShipmentPlanFile(file);
        break;
      case "product_shipment_order":
        setProductShipmentOrderFile(file);
        break;
      case "customer_acceptance_report":
        setCustomerAcceptanceReportFile(file);
        break;
    }
    return false;
  };

  const save = async () => {
    try {
      const values = await productDeliveryForm.validateFields();
      const formData = new FormData();
      setUploading(true);

      // 固定字段
      formData.append('id', productDeliveryDetail.id);
      formData.append('shipment_order_id', values.shipment_order_id);
      formData.append('delivery_address', values.delivery_address);

      // 基础字段处理（已移除产品相关字段）
      const basicFields = ['sales_order_id'];
      basicFields.forEach(field => {
        if (values[field] !== null && values[field] !== undefined) {
          formData.append(field, values[field]);
        }
      });

      // 日期字段处理
      if (values.shipment_date) {
        formData.append('shipment_date', dayjs(values.shipment_date).format('YYYY-MM-DD'));
      }

      // 文件字段处理（保持原有逻辑）
      const fileFields = [
        { state: deliveryListFile, detail: productDeliveryDetail.delivery_list, name: 'delivery_list' },
        { state: factoryAcceptanceReportFile, detail: productDeliveryDetail.factory_acceptance_report, name: 'factory_acceptance_report' },
        { state: shipmentPlanFile, detail: productDeliveryDetail.shipment_plan, name: 'shipment_plan' },
        { state: productShipmentOrderFile, detail: productDeliveryDetail.product_shipment_order, name: 'product_shipment_order' },
        { state: customerAcceptanceReportFile, detail: productDeliveryDetail.customer_acceptance_report, name: 'customer_acceptance_report' }
      ];

      fileFields.forEach(({ state, detail, name }) => {
        if (state) {
          formData.append(name, state);
        } else if (detail) {
          formData.append(name, detail);
        }
      });

      // 发送请求
      fetch("/admin/productDelivery/updateOrder", {
        method: "POST",
        body: formData,
        headers:{
          Authorization: `Bearer ${JSON.parse(localStorage.getItem('user')).token}`
        }        
      }).then(response => response.json())
        .then(data => {
          if (data.code === 200) {
            notification.success({ message: data.msg });
          } else {
            notification.error({ message: data.msg || "上传失败" });
          }
          setTimeout(() => setUploading(false), 300);
        });
    } catch (errorInfo) {
      notification.error({ message: "请检查填写信息是否有误" });
    }
  };

  useEffect(() => {
    // 获取ID参数
    const hash = window.location.hash.slice(1);
    const queryString = hash.split('?')[1];
    let id = null;
    
    if (queryString) {
      const queryParams = new URLSearchParams(queryString);
      id = parseInt(queryParams.get('id'));
    } else {
      return;
    }

    // 加载数据
    request("/admin/productDelivery/getProductDeliveryInfo", {
      method: "POST",
      mode: 'cors',
      body: { id }
    }).then(data => {
        if (data.code === 200) {
          const formattedData = {
            ...data.data,
            shipment_date: data.data.shipment_date ? dayjs(data.data.shipment_date) : null,
          };
          setproductDeliveryDetail(formattedData);
          productDeliveryForm.setFieldsValue(formattedData);
          notification.success({ message: data.msg });
        } else {
          notification.open({ message: "未知错误" });
        }
      });
  }, []);

  return (
    <div style={{    
      height: "94%", 
      backgroundColor: `#F1F1F1`,
      right: "1%",
      top: "4vh",
      overflow: "hidden",
      backgroundSize: "100% 100%", 
      width: collapsed ? "94%" : "84%", 
      position: "absolute",  
      color: "white", 
      fontSize: "0.8rem"
    }}>
      <div style={styles.kshcontainer}>
        <div style={{
          fontSize: "0.7rem", 
          position: "relative", 
          width: "96%", 
          marginLeft: "2%", 
          backgroundColor: "", 
          display: "flex",
          textIndent: "1rem", 
          justifyContent: "flex-start", 
          alignContent: "flex-start", 
          flexWrap: "wrap"
        }}>
          <Card style={{ width: "100%", marginTop: "2vh" }}>
            <div style={{ maxHeight: "75vh", overflowY: "scroll" }}>
              <div>
                <Form style={{ width: "95%" }} form={productDeliveryForm}>
                  {/* 不可改动区域 */}
                  <h3 style={{ 
                    color: '#1890ff', 
                    margin: '24px 0 12px', 
                    fontSize: 16, 
                    display: 'flex', 
                    alignItems: 'center' 
                  }}>
                    <InfoCircleOutlined style={{ marginRight: 6 }} /> 不可改动
                  </h3>
                  <Divider />
                  
                  <Form.Item name="shipment_order_id" label="出货单号（不可改动）">
                    <Input placeholder='出货单号为空' disabled />
                  </Form.Item>
                  
                  <Form.Item name="delivery_address" label="送货地址（不可改动）">
                    <Input placeholder='送货地址为空' disabled />
                  </Form.Item>

                  {/* 其他信息区域 */}
                  <h3 style={{ 
                    color: '#1890ff', 
                    margin: '24px 0 12px', 
                    fontSize: 16, 
                    display: 'flex', 
                    alignItems: 'center' 
                  }}>
                    <InfoCircleOutlined style={{ marginRight: 6 }} /> 其他信息
                  </h3>
                  <Divider />
                  
                  <Form.Item name="shipment_date" label="出货日期">
                    <DatePicker placeholder='出货日期为空' />
                  </Form.Item>
                  
                  <Form.Item name="sales_order_id" label="销售单号">
                    <Input disabled maxLength={50} showCount placeholder='销售单号为空' />
                  </Form.Item>

                  {/* 附件上传区域 */}
                  <h3 style={{ 
                    color: '#1890ff', 
                    margin: '24px 0 12px', 
                    fontSize: 16, 
                    display: 'flex', 
                    alignItems: 'center' 
                  }}>
                    <InfoCircleOutlined style={{ marginRight: 6 }} /> 附件上传（新上传的文件将覆盖旧文件，但不会影响到其他表单引用旧文件）
                  </h3>
                  <Divider />

                  <Row gutter={[16, 16]}>
                    {/* 第一行第一个 */}
                    <Col xs={24} sm={12}>
                      <Form.Item name="delivery_list" label="交货清单">
                        {productDeliveryDetail.delivery_list ? (
                          <div>
                            <a href={`${localUrl}${productDeliveryDetail.delivery_list}`}>
                              <Button icon={<DownloadOutlined />}>下载文件</Button>
                            </a>
                          </div>
                        ) : (
                          <div>没有上传交货清单</div>
                        )}
                        <Upload
                          maxCount={1}
                          beforeUpload={handleBeforeUpload('delivery_list')}
                          onRemove={() => { setDeliveryListFile(null); return true; }}
                          fileList={deliveryListFile ? [{
                            uid: deliveryListFile.uid || Date.now().toString(),
                            name: deliveryListFile.name,
                            status: 'done'
                          }] : []}
                        >
                          <Button style={{ marginTop: "2vh" }} icon={<UploadOutlined />}>重新上传文件</Button>
                        </Upload>
                      </Form.Item>
                    </Col>
                    
                    {/* 第一行第二个 */}
                    <Col xs={24} sm={12}>
                      <Form.Item name="factory_acceptance_report" label="出厂验收报告">
                        {productDeliveryDetail.factory_acceptance_report ? (
                          <div>
                            <a href={`${localUrl}${productDeliveryDetail.factory_acceptance_report}`}>
                              <Button icon={<DownloadOutlined />}>下载文件</Button>
                            </a>
                          </div>
                        ) : (
                          <div>没有上传出厂验收报告</div>
                        )}
                        <Upload
                          maxCount={1}
                          beforeUpload={handleBeforeUpload('factory_acceptance_report')}
                          onRemove={() => { setFactoryAcceptanceReportFile(null); return true; }}
                          fileList={factoryAcceptanceReportFile ? [{
                            uid: factoryAcceptanceReportFile.uid || Date.now().toString(),
                            name: factoryAcceptanceReportFile.name,
                            status: 'done'
                          }] : []}
                        >
                          <Button style={{ marginTop: "2vh" }} icon={<UploadOutlined />}>重新上传文件</Button>
                        </Upload>
                      </Form.Item>
                    </Col>
                    
                    {/* 第二行第一个 */}
                    <Col xs={24} sm={12}>
                      <Form.Item name="shipment_plan" label="出货计划">
                        {productDeliveryDetail.shipment_plan ? (
                          <div>
                            <a href={`${localUrl}${productDeliveryDetail.shipment_plan}`}>
                              <Button icon={<DownloadOutlined />}>下载文件</Button>
                            </a>
                          </div>
                        ) : (
                          <div>没有上传出货计划</div>
                        )}
                        <Upload
                          maxCount={1}
                          beforeUpload={handleBeforeUpload('shipment_plan')}
                          onRemove={() => { setShipmentPlanFile(null); return true; }}
                          fileList={shipmentPlanFile ? [{
                            uid: shipmentPlanFile.uid || Date.now().toString(),
                            name: shipmentPlanFile.name,
                            status: 'done'
                          }] : []}
                        >
                          <Button style={{ marginTop: "2vh" }} icon={<UploadOutlined />}>重新上传文件</Button>
                        </Upload>
                      </Form.Item>
                    </Col>
                    
                    {/* 第二行第二个 */}
                    <Col xs={24} sm={12}>
                      <Form.Item name="product_shipment_order" label="产品出货单">
                        {productDeliveryDetail.product_shipment_order ? (
                          <div>
                            <a href={`${localUrl}${productDeliveryDetail.product_shipment_order}`}>
                              <Button icon={<DownloadOutlined />}>下载文件</Button>
                            </a>
                          </div>
                        ) : (
                          <div>没有上传产品出货单</div>
                        )}
                        <Upload
                          maxCount={1}
                          beforeUpload={handleBeforeUpload('product_shipment_order')}
                          onRemove={() => { setProductShipmentOrderFile(null); return true; }}
                          fileList={productShipmentOrderFile ? [{
                            uid: productShipmentOrderFile.uid || Date.now().toString(),
                            name: productShipmentOrderFile.name,
                            status: 'done'
                          }] : []}
                        >
                          <Button style={{ marginTop: "2vh" }} icon={<UploadOutlined />}>重新上传文件</Button>
                        </Upload>
                      </Form.Item>
                    </Col>
                    
                    {/* 第三行单独一个 */}
                    <Col xs={24} sm={12}>
                      <Form.Item name="customer_acceptance_report" label="客户验收报告">
                        {productDeliveryDetail.customer_acceptance_report ? (
                          <div>
                            <a href={`${localUrl}${productDeliveryDetail.customer_acceptance_report}`}>
                              <Button icon={<DownloadOutlined />}>下载文件</Button>
                            </a>
                          </div>
                        ) : (
                          <div>没有上传客户验收报告</div>
                        )}
                        <Upload
                          maxCount={1}
                          beforeUpload={handleBeforeUpload('customer_acceptance_report')}
                          onRemove={() => { setCustomerAcceptanceReportFile(null); return true; }}
                          fileList={customerAcceptanceReportFile ? [{
                            uid: customerAcceptanceReportFile.uid || Date.now().toString(),
                            name: customerAcceptanceReportFile.name,
                            status: 'done'
                          }] : []}
                        >
                          <Button style={{ marginTop: "2vh" }} icon={<UploadOutlined />}>重新上传文件</Button>
                        </Upload>
                      </Form.Item>
                    </Col>
                  </Row>
                  
                  <Button type='primary' onClick={save}>保存更改</Button>
                </Form>
              </div>
            </div>
          </Card>
          
          {/* 上传加载模态框 - 保持原有属性和样式 */}
          <Modal
            open={uploading}
            centered
            closable={false}  // 保持原有属性名
            footer={null}
            maskClosable={false}  // 保持原有属性名
            width={400}
            bodyStyle={{ textAlign: 'center', padding: '30px 20px' }}
          >
            <Spin />
            <div style={{ marginTop: 20, fontSize: 16, fontWeight: 'bold', color: '#333' }}>
              上传中
            </div>
            <div style={{ marginTop: 10, color: '#666' }}>
              请勿关闭页面或进行其他操作
            </div>
          </Modal>
        </div>
      </div>
    </div>
  );
};

export default UpdateProductDelivery;

// 保留完整样式定义，确保页面布局不变
const styles = {
  maincontainer: {
    height: "100vh", 
    backgroundColor: `white`,
    backgroundSize: "100% 100%", 
    width: "100%", 
    position: "absolute",
    color: "white", 
    fontSize: "0.8rem"
  },
  topcontainer: {
    width: "100%", 
    height: "10vw", 
    backgroundImage: "linear-gradient(to bottom,#e4e5eb , white)", 
    paddingTop: "3vw",
    position: "relative", 
    fontSize: "0.89rem", 
    textIndent: "2rem", 
    fontWeight: "800", 
    color: "#a91f24", 
    borderRadius: "0 0 15px 15px"
  },
  butdcstyle: { 
    paddingLeft: "1vw",
    paddingRight: "1vw",
    height: "2vw", 
    position: "absolute", 
    right: "1%", 
    top: "0%", 
    backgroundColor: "#a91f24", 
    fontSize: "0.8vw", 
    borderRadius: "0.4rem", 
    borderRadius: "0 0 0.3vw 0.3vw" 
  },
  butmainstyle: {
    paddingLeft: "1vw", 
    height: "2vw", 
    position: "absolute", 
    right: "6.5%",
    backgroundColor: "#a91f24", 
    fontSize: "0.8vw", 
    borderRadius: "0.4rem", 
    borderRadius: "0 0 0.3vw 0.3vw" 
  },
  butbackstyle: { 
    borderRadius: "0.4rem", 
    backgroundColor: "#a91f24", 
    height: "2vw", 
    position: "absolute", 
    right: "12%",
    fontSize: "0.8vw", 
    borderRadius: "0 0 0.3vw 0.3vw"
  },
  kshcontainer: {
    width: "98%", 
    height: "95%", 
    position: "absolute", 
    top: "3%", 
    left: "1%", 
    backgroundColor: "white", 
    color: "black",
    borderRadius: "10px",
  },
};
    